package com.corn.flink.lesson5;

import com.corn.flink.lesson4.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.triggers.TriggerResult;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;

/**
 * @author JimWu
 * @date 2023/3/16 14:15
 **/
public class TrigerDemo {
    /**
     * 在日常业务场景中，我们经常会开比较大的窗口来计算每个窗口的
     * pv 或者 uv 等数据。但窗口开的太大，会使我们看到计算结果的时间间隔变长。所以我们可以
     * 使用触发器，来隔一段时间触发一次窗口计算
     */
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<Event> ds = env.fromElements(
                new Event("add", 1000),
                new Event("delete", 2000),
                new Event("update", 3000),
                new Event("select", 5000),
                new Event("add", 6000),
                new Event("delete", 7000),
                new Event("select", 8000),
                new Event("select", 9000),
                new Event("select", 10000),
                new Event("select", 11000)
        );


        ds.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event element, long recordTimestamp) {
                                return element.timestamp;
                            }
                        }))
                .keyBy(data -> data.type)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .trigger(new Trigger<Event, TimeWindow>() {
                    /**
                     * onElement
                     * TriggerResult 四种状态
                     * CONTINUE 继续 无动作
                     * FIRE_AND_PURGE 触发计算并清空窗口数据 销毁窗口
                     * FIRE 触发计算不清空窗口
                     * PURGE 清空窗口所有数据 销毁窗口
                     */
                    // 当窗口每达到一个元素触发
                    @Override
                    public TriggerResult onElement(Event element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {
//                        ValueState<Boolean> state = ctx.getPartitionedState(new ValueStateDescriptor<Boolean>("first_event", Boolean.class));
//                        if (state.value() == null) {
                        for (long i = window.getStart(); i < window.getEnd(); i =
                                i + 1000L) {
//                                ctx.registerEventTimeTimer(i);
                            return TriggerResult.FIRE;
                        }
//                            state.update(true);
//                        }
                        return TriggerResult.CONTINUE;
                    }

                    // 注册处理时间时候触发
                    @Override
                    public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
                        return TriggerResult.CONTINUE;
                    }

                    // 注册时间时间时候触发
                    @Override
                    public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
                        return TriggerResult.CONTINUE;
                    }

                    // 窗口销毁触发
                    @Override
                    public void clear(TimeWindow window, TriggerContext ctx) throws Exception {

                    }
                })
                .process(new ProcessWindowFunction<Event, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Event> elements, Collector<String> out) throws Exception {
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        out.collect(new Timestamp(start) + " - " + new Timestamp(end) + " -> " + s + " : " + elements.spliterator().getExactSizeIfKnown());
                    }
                })
                .print();


        env.execute();
    }
}
